import React, {Component} from "react";
import Controller from "../components/Controller";
import GamePanel from "../components/GamePanel";
import {isSuccess as isSuccessFun} from "../utils/five-success";
import {message, Modal} from "antd";
import {deepClone} from "../utils/common";

export default class FiveGame extends Component {
    constructor() {
        super();

        this.state = this.initState()
    }

    initState(){
        // 构建出了一个15 * 15二维数组，数组的每一项是0
        const checkerboardData = []
        for (let i = 0; i < 15; i++) {
            checkerboardData.push(new Array(15).fill(0))
        }
        return {
            checkerboardData,
            isBlack: true,
            isSuccess:false,
            // 记录每一次的状态
            history:[]
        }
    }

    playChess(row, col) {
        console.log(row)
        console.log(col)
        const {isBlack, checkerboardData,history} = this.state;
        if (this.state.isSuccess) {
            message.info('游戏已经结束，请开始下一把吧');
            return;
        }

        // 后续去修改了这些内容
        history.push({
            ...this.state,
            checkerboardData:deepClone(checkerboardData,[])
        })

        if (isBlack) {
            checkerboardData[row][col] = "1";
        } else {
            checkerboardData[row][col] = "2";
        }
        // 落子之后才能拿判断胜负
        // 胜负条件和这颗棋子有关
        // 判断这颗棋子在横轴，纵轴和两个斜着的方向有没有连城五颗
        const isSuccess = isSuccessFun(checkerboardData, row, col);
        if (isSuccess) {
            // 给用户有个提示
            Modal.success({
                content: `恭喜${isBlack?'黑棋':'白棋'}获胜了`,
            });
        }
        this.setState({
            checkerboardData,
            isSuccess,
            isBlack: !isBlack,
            history
        });
    }

    handleRestart(){
        this.setState(this.initState())
    }
    handleRegretChess(){
        if (this.state.history.length === 0) {
            message.info("没有棋可以悔了")
            return;
        }
        const oldState = this.state.history.pop();

        this.setState(oldState)
    }


    render() {
        return (
            <div style={{padding: "25px"}}>
                <div className='bgc'></div>
                <Controller restart={this.handleRestart.bind(this)} regretChess={this.handleRegretChess.bind(this)} />
                <GamePanel checkerboardData={this.state.checkerboardData} playChess={this.playChess.bind(this)}/>
            </div>
        );
    }
}